#!/usr/bin/python
#-*- coding: utf-8 -*-

# Pymaxe
# (c) 2010 Ovidiu D. Niţan
# Dupa o idee de E. H.

from __future__ import with_statement
import gtk, gobject, pango					# importam modulul pentru interfata grafica
import gtk.glade						# importam modulul pentru incarcarea interfetei din fisiere glade
import urllib, urllib2, time
import os, sys, shutil, re, platform
import threading
from thread2 import Thread
import datetime, time
import subprocess
import zipfile
#import logoshape
import gettext, locale
from SettingManager import config
if os.environ.get("APPDATA"):					# suntem pe Windows
	import gettext_windows

def initLangs():
	if os.environ.get("APPDATA"):	
		gettext_windows.setup_env()
	GETTEXT_DOMAIN = 'Pymaxe'
	try:
		LOCALE_PATH = os.path.join(os.path.dirname(os.path.abspath( __file__ )), 'i18n')
	except:
		LOCALE_PATH = 'i18n'
	locale.setlocale(locale.LC_ALL, '')
	for module in gtk.glade, gettext:
		module.bindtextdomain(GETTEXT_DOMAIN, LOCALE_PATH)
		module.textdomain(GETTEXT_DOMAIN)

def translate(text):
	text = unicode(text, errors='ignore')
	try:
		return unicode(gettext.gettext(text), errors='ignore')
	except:
		return gettext.gettext(text)

initLangs()	
import __builtin__
__builtin__._ = translate

if os.environ.get("APPDATA"):
	sys.stdout = open(os.environ.get("APPDATA") + '\\pymaxe\\pymaxe.log', 'w')
	sys.stderr = open(os.environ.get("APPDATA") + '\\pymaxe\\pymaxe.log', 'w')
	from multiprocessing import Process, freeze_support
	cfgfile = os.environ.get("APPDATA") + '\\pymaxe\\pymaxe.ini';
else:
	cfgfile = os.getenv("HOME") + '/.pymaxe/pymaxe.cfg';
 
#gobject.threads_init()
gtk.gdk.threads_init()

if os.environ.get("APPDATA"):
	ffmpeg = 'ffmpeg.exe'
else:
	ffmpeg = '/usr/bin/ffmpeg'
downDict = {}	
curver = 0.39

def strip_win32_incompat(string, BAD = '\:*?;"<>|'):
	"""Strip Win32-incompatible characters.
	This only works correctly on Unicode strings.
	"""
	string = unicode(string,'latin-1')
	new = u"".join(map(lambda s: (s in BAD and "_") or s, string))
	parts = new.split(os.sep)
	def fix_end(string):
		return re.sub(r'[\. ]$', "_", string) 
	return unicode(os.sep).join(map(fix_end, parts))
	
class Main:
	def __init__(self):
		self.gui = gtk.Builder()
		self.gui.add_from_file('pymaxe.glade')
		self.gui.connect_signals({
		"on_pymaxe_destroy" : self.on_pymaxe_destroy,
		"on_about" : self.on_about,
		"hide_about" : self.hide_about,
		"search_music" : self.search_music,
		"search_me" : self.search_me,
		"video_details" : self.video_details,
		"download_details" : self.download_details,
		"hide_details" : self.hide_details,
		"get_video_details" : self.get_video_details,
		"saveTo" : self.saveTo,
		"on_preferences" : self.on_preferences,
		"hide_settings" : self.hide_settings,
		"plugin_details" : self.plugin_details,
		"hide_plugin" : self.hide_plugin,
		"select_folder" : self.select_folder,
		"saveSettings" : self.saveSettings,
		"removePlugin" : self.removePlugin,
		"activateTree" : self.activateTree,
		"pluginConfig" : self.pluginConfig,
		"activateCheck" : self.activateCheck,
		"splashClick" : self.splashClick,
		"pluginInstall" : self.pluginInstall,
		"hide_updater" : self.hide_updater,
		"gotoWebpage" : self.gotoWebpage,
		"downloadVersion" : self.downloadVersion,
		"showDD" : self.showDD,
		"openFile" : self.openFile,
		"openFolder" : self.openFolder,
		"elimina" : self.elimina,
		"deletehdd" : self.deletehdd,
		"donate" : self.donate,
		"menuitem5_activate_cb" : self.menuitem5_activate_cb,
		"openSourceWWW" : self.openSourceWWW,
		"copyStreamURL" : self.copyStreamURL,
		"chooseMP" : self.chooseMP,
		"showStream" : self.showStream,
		"cancelOperation" : self.cancelOperation,
		"showChangelog" : self.showChangelog,
		"clearSearchEntry" : self.clearSearchEntry,
		"resetEntryStyle" : self.resetEntryStyle,
		"updatePluginsButtons" : self.updatePluginsButtons
		});
		self.isWorking = False
		self.doConvert = False
		self.converting = False
		self.breakDownload = False
		self.searchThread = None
		self.detailsThread = None
		self.progressbar = self.gui.get_object("progressbar1");
		self.pulsar = gobject.timeout_add(50, self.pulse)
		self.gui.get_object('treeviewcolumn2').clicked()
		try:
			showSplash = config.getboolean('General', 'splashScreen')
		except:
			showSplash = True
		self.treeview = self.gui.get_object("treeview1");
		if showSplash:
			self.gui.get_object('window1').show()
			#pixmap, mask = gtk.gdk.pixmap_create_from_xpm_d(self.gui.get_object('window1').window, None, logoshape.pymaxe_splash)
			#self.gui.get_object('window1').shape_combine_mask(mask, 0, 0)
			self.showme = gobject.timeout_add(2000, self.showgui)
		else:
			self.showme = gobject.timeout_add(100, self.showgui)
		try:
			checkUpdates = config.getboolean('General', 'checkUpdates')
		except:
			checkUpdates = True
		if checkUpdates:
			Thread(target=self.checkUpdates).start()
		self.sites = {}
		self.readPreferences()
		initLangs()
		iter = self.gui.get_object('liststore2').get_iter_root()
		while (iter):
			pluginName = self.gui.get_object('liststore2').get_value(iter, 3)
			checked = self.gui.get_object('liststore2').get_value(iter, 0)
			if checked:
				try:
					self.plugin[pluginName].start(self)
				except Exception, e:
					print 'Plugin ' + pluginName + 'could not be started'
					print e
			iter = self.gui.get_object('liststore2').iter_next(iter)
		try:
			updatePls = config.getboolean('General', 'updatePlugins')
		except:
			updatePls = True
		if updatePls:
			import pluginUpdater
			pluginUpdater.updatePlugins(self)
		initLangs()
		gtk.gdk.threads_enter()
		gtk.main();
		gtk.gdk.threads_leave()
		
	def showgui(self):
		self.gui.get_object('treeviewcolumn2').set_title(_('Title'))
		self.gui.get_object('treeviewcolumn3').set_title(_('Length'))
		self.gui.get_object('aboutdialog').set_license(open('gpl-3.0.txt', 'r').read())
#		self.gui.get_object('entry1').modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("gray"))
		self.gui.get_object('entry1').modify_font(pango.FontDescription("Bold Italic"))
		self.entry1text = self.gui.get_object('entry1').get_text()
		self.gui.get_object('pymaxe').show()
		gobject.source_remove(self.showme)
		hidesplash = gobject.timeout_add(1000, self.gui.get_object('window1').hide)
		try:
			saveIN = config.get('General', 'saveIn')
		except:
			if os.environ.get("APPDATA"):
				saveIN = os.environ.get("USERPROFILE") + '\\Desktop'
			else:
				saveIN = os.environ.get("HOME") + '/Desktop'
		self.gui.get_object('entry2').set_text(saveIN)
	
	def checkUpdates(self):
		try:
			req = urllib2.Request('http://redoxwap.freehostia.com/pymaxe_update.php?action=last_version')
			response = urllib2.urlopen(req)
			sdata = response.read()
			self.lastVer = sdata
			self.lastVer = float(self.lastVer)
			if curver < self.lastVer:
				gobject.idle_add(self.newVersion, self.lastVer)
		except Exception, e:
			pass
		
	def newVersion(self, lastVer):
		vcstring = _('<b>Current version: </b> %s') % str(curver)
		vnstring = _('<b>New version: </b> %s') % str(lastVer)
		self.gui.get_object('label14').set_markup(vcstring)
		self.gui.get_object('label29').set_markup(vnstring)
		self.gui.get_object('updater').show();
		
	def showChangelog(self, obj):
		Thread(target=self.getChangelog).start()
		
	def getChangelog(self):
		req = urllib2.Request('http://redoxwap.freehostia.com/pymaxe_update.php?action=get_changelog&v=' + str(self.lastVer))
		response = urllib2.urlopen(req)
		whatsnew = response.read()
		self.gui.get_object('label31').set_text(whatsnew)
	
	def hide_updater(self, obj=None, event=None):
		self.gui.get_object('updater').hide()
		
	def gotoWebpage(self, obj):
		if platform.system() == 'Linux':
			subprocess.call(['xdg-open', 'http://www.pymaxe.com'])
		else:
			os.startfile('http://www.pymaxe.com')
		self.hide_updater()

	def donate(self, obj):
		if platform.system() == 'Linux':
			subprocess.call(['xdg-open', 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2Z3VX4N9DFFMJ'])
		else:
			os.startfile('https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2Z3VX4N9DFFMJ')
		
	def downloadVersion(self, obj):
		if platform.system() == 'Linux':
			distro = platform.linux_distribution()[0].lower()
			debdistro = ['ubuntu', 'linuxmint', 'mepis', 'dreamlinux', 'knoppix', 'debian']
			rpmdistro = ['fedora', 'mandriva', 'suse', 'opensuse', 'redhat']
			if distro in debdistro:
				subprocess.call(['xdg-open', 'http://www.pymaxe.com/files/latest/pymaxe.deb'])
			elif distro in rpmdistro:
				subprocess.call(['xdg-open', 'http://www.pymaxe.com/files/latest/pymaxe.rpm'])
			else:
				subprocess.call(['xdg-open', 'http://www.pymaxe.com/files/latest/pymaxe.tar.gz'])
		elif os.environ.get("APPDATA"):
			os.startfile('http://www.pymaxe.com/files/latest/pymaxe.exe')
		else:
			subprocess.call(['xdg-open', 'http://www.pymaxe.com/files/latest/pymaxe.tar.gz'])
		self.on_pymaxe_destroy(None);
		
	def on_about(self, obj):
		self.about = self.gui.get_object("aboutdialog");
		self.about.set_version(str(curver))
		self.about.run()
		
	def hide_about(self, obj, event=None):
		self.about.hide();
		return True
		
	def search_music(self, obj):
		searchingText = _('Searching...')
		self.gui.get_object('progressbar1').set_text(searchingText)
		if self.gui.get_object('entry1').get_text() != self.entry1text:
			if self.gui.get_object("entry1").get_text()[:7] == 'http://':
				self.get_video_details(self.gui.get_object("entry1").get_text())
			else:
				self.cancelOperation(None)
				self.gui.get_object('notebook2').set_current_page(0)
				self.liststore = self.gui.get_object("liststore1");
				self.liststore.clear();
				self.sstring = self.gui.get_object("entry1").get_text();
				self.cancelOperation(None)
				if (self.gui.get_object("radiomenuitem1").get_active()):
					self.searchThread = Thread(target=self.do_search, args=(self.sstring, 'all'))
					self.searchThread.start()
				else:
					for radio in self.gui.get_object('radiomenuitem1').get_group():
						if radio.get_active():
							#usePlugin = radio.get_label()
							usePlugin = radio.get_children()[0].get_label()
					self.searchThread = Thread(target=self.do_search, args=(self.sstring, usePlugin))
					self.searchThread.start()
		
	def do_search(self, string, plugin):
		if string == '':
			return
		if plugin == 'all':
			searchPlugins = self.gui.get_object('radiomenuitem1').get_group()
			self.searchThreads = []
			self.isWorking = True
			for x in searchPlugins:
				try:
				  pluginName = x.get_children()[0].get_label()
				except:
					pass
				try:
					thr = Thread(target=self.plugin[pluginName].search, args=(self, string))
					thr.start()
					self.searchThreads.append(thr)
					
				except:
					pass
			while True:
				for x in self.searchThreads:
					index = self.searchThreads.index(x)
					if self.searchThreads[index].is_alive() == False:
						self.searchThreads.pop(index)
				if len(self.searchThreads) == 0:
					self.isWorking = False
					self.searchThread = None
					return
				time.sleep(0.2)

		else:
			self.isWorking = True
			self.plugin[plugin].search(self, string)
			self.isWorking = False
		initLangs()
	
	def pulse(self):
		try:
			if self.isWorking == True:
				gobject.idle_add(self.gui.get_object('hbox25').show);
				gobject.idle_add(self.progressbar.pulse);
			else:
				gobject.idle_add(self.gui.get_object('hbox25').hide);
		except:
			pass
		return True
			
	def addToList(self, array):
		self.liststore.append(array);
	
	def video_details(self, obj, event):
		#self.isWorking = False
		if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
			gobject.idle_add(self.v_details)
		
		if event.button == 3:
			treeselection = self.treeview.get_selection()
			(model, iter) = treeselection.get_selected()
			if iter:
				self.gui.get_object('menu4').popup(None, None, None, event.button, event.time)
				
	def download_details(self, obj, event):
		if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
			gobject.idle_add(self.openFile, None)
		
		if event.button == 3:
			treeselection = self.gui.get_object('treeview3').get_selection()
			(model, iter) = treeselection.get_selected()
			if iter:
				self.gui.get_object('menu5').popup(None, None, None, event.button, event.time)
				
	def menuitem5_activate_cb(self, obj):
		gobject.idle_add(self.v_details)
	
	def v_details(self):
		treeselection = self.treeview.get_selection()
		(model, iter) = treeselection.get_selected()
		if iter:
			url = self.liststore.get_value(iter, 3);
			titlu = self.liststore.get_value(iter, 1)
			durata = self.liststore.get_value(iter, 2)
			initLangs()
			citescdatele = _('Reading data from server...')
			self.gui.get_object('progressbar1').set_text(citescdatele)
			self.isWorking = True
			self.detailsThread = Thread(target=self.getDetails, args=(url, durata))
			self.detailsThread.start()
			self.treeview.set_sensitive(False)
			self.gui.get_object('toolbar1').set_sensitive(False)
			self.gui.get_object('menubar1').set_sensitive(False)
			self.gui.get_object('scrolledwindow1').set_sensitive(False)
			
	def getDetails(self, url, durata=None):
		for x in self.sites:
			mask = self.sites[x]
			if url.find(mask) != -1:
				self.plugin[x].getDetails(self, url)
				return
		initLangs()
		print _("No plugin to download!")
		self.isWorking = False
		self.restoreState()
				
	def showDetails(self, data, widget=None, durlFunc=None):
		pluginGUI = self.gui.get_object('hbox14').get_children()
		for x in pluginGUI:
			x.destroy()
		#self.gui.get_object('radiobutton1').set_active(True)
		self.gui.get_object('vbox3').set_sensitive(True)
		#self.gui.get_object('checkbutton5').set_sensitive(False)
		try:
			autoOpen = config.getboolean('General', 'autoOpen')
		except:
			autoOpen = False
		self.gui.get_object('checkbutton6').set_active(autoOpen)
		titlu = data['titlu']
		durata = data['durata']
		url = data['url']
		tip  = data['tip']
		format = data['format']
		self.gui.get_object('label2').set_markup('<span size="x-large"><b>'+ titlu.replace('&', '&amp;') +'</b></span>')
		self.gui.get_object('label4').set_markup(_('Length: ') + durata)
		self.gui.get_object('label10').set_markup('<a href="' + gobject.markup_escape_text(url) + '">' + gobject.markup_escape_text(url) + '</a>')
		if os.environ.get("APPDATA"):
			if not os.path.isdir(self.gui.get_object('entry2').get_text()):
				self.gui.get_object('entry2').set_text(os.path.dirname(self.gui.get_object('entry2').get_text()) + '\\' + strip_win32_incompat(titlu.replace('&', '&amp;')) + data['tip'])
			else:
				self.gui.get_object('entry2').set_text(self.gui.get_object('entry2').get_text() + '\\' + strip_win32_incompat(titlu.replace('&', '&amp;')) + data['tip'])
		else:
			if not os.path.isdir(self.gui.get_object('entry2').get_text()):
				self.gui.get_object('entry2').set_text(os.path.dirname(self.gui.get_object('entry2').get_text()) + '/' + titlu.replace('/', '_') + data['tip'])
			else:
				self.gui.get_object('entry2').set_text(self.gui.get_object('entry2').get_text() + '/' + titlu.replace('/', '_') + data['tip'])
		self.gui.get_object('label12').set_text(format)
		if widget != None:
			self.gui.get_object('hbox14').show()
			self.gui.get_object('hbox14').pack_start(widget, True, True, 0)
		self.gui.get_object('details').resize(1, 1)
		try:
			self.gui.get_object('button3').disconnect(self.butConnection)
		except:
			pass
		self.butConnection = self.gui.get_object('button3').connect("clicked", self.downQueue, data, durlFunc)
		self.gui.get_object('details').show()
	
	def hide_details(self, obj, event=None):
		self.gui.get_object('details').hide()
		return True
		
	def get_video_details(self, url):
		self.isWorking = True
		for x in self.sites:
			mask = self.sites[x]
			if url.find(mask) != -1:
				Thread(target=self.plugin[x].getDetails, args=(self, url)).start()
				return True
				break
		initLangs()
		print _("There's no plugin for using with this URL!")
		self.isWorking = False
		self.restoreState()
	
	def search_me(self, obj, event):
		if event.keyval	== 65293:
			self.search_music(obj)
			
	def saveTo(self, obj, event=None):
		chooser = gtk.FileChooserDialog(title=_('Save as...'),action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
                chooser.set_current_name(strip_win32_incompat(os.path.basename(self.gui.get_object('entry2').get_text())))
                chooser.set_do_overwrite_confirmation(True)
		chooser.set_current_folder(os.path.dirname(self.gui.get_object('entry2').get_text()))
                response = chooser.run()
                if response == gtk.RESPONSE_OK:
			self.gui.get_object('entry2').set_text(chooser.get_filename())
		chooser.destroy()

	def downQueue(self, obj, data, durlFunc):
		self.gui.get_object('progressbar2').set_fraction(0)
		if durlFunc:
			data['downurl'] = durlFunc()
		downurl = data['downurl']
		data['saveas'] = self.gui.get_object('entry2').get_text() + ''
		data['ID'] = str(time.time())
		data['downloading'] = 'True'
		data['convert'] = str(self.doConvert)
		if os.path.exists(data['saveas']):
			initLangs()
			dialog = gtk.MessageDialog(parent=self.gui.get_object('pymaxe'), flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_YES_NO, message_format=_('File already exists. Overwrite?'));
			dialog.set_title(_('Warning'));
			resp = dialog.run();
			dialog.destroy();
			if resp == -9:
				return True
		iter = self.gui.get_object('liststore3').append([gtk.gdk.pixbuf_new_from_file('img/download.png'), data['titlu'], data])
		self.gui.get_object('details').hide()
		self.gui.get_object('notebook2').set_current_page(1)
		downDict[data['ID']] = Downloader()
		Thread(target=downDict[data['ID']].download, args=(downurl, data, self.converter, self.gui.get_object('checkbutton6').get_active(), iter, self.succes, self.error)).start()
		initLangs()
		treeselection = self.gui.get_object('treeview3').get_selection()
		treeselection.select_iter(iter)
		self.showDD(self.gui.get_object('treeview3'))
		self.gui.get_object('treeview3').scroll_to_cell(self.gui.get_object('liststore3').get_path(iter))

	def showDD(self, obj):
		#self.gui.get_object('button17').set_sensitive(False)
		self.gui.get_object('progressbar2').hide()
		try:
			gobject.source_remove(self.progressMonitor)
		except:
			pass
		try:
			treeselection = obj.get_selection()
			(model, iter) = treeselection.get_selected()
			data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
			title = self.gui.get_object('liststore3').get_value(iter, 1)
			self.gui.get_object('label39').set_text(data['downurl'])
			self.gui.get_object('label40').set_text(data['saveas'])
			self.Progress(iter)
			self.progressMonitor = gobject.timeout_add(500, self.Progress, iter)
			if data['downloading'] == 'Full':
				self.gui.get_object('button6').set_sensitive(True)
				self.gui.get_object('menuitem11').set_sensitive(True)
				self.gui.get_object('menuitem12').set_sensitive(True)
				self.gui.get_object('menuitem15').set_sensitive(True)
			else:
				self.gui.get_object('button6').set_sensitive(False)
				self.gui.get_object('menuitem11').set_sensitive(False)
				self.gui.get_object('menuitem12').set_sensitive(False)
				self.gui.get_object('menuitem15').set_sensitive(False)
			self.gui.get_object('button17').set_sensitive(True)
		except Exception, e:
			pass
		self.gui.get_object('progressbar2').show()

	def Progress(self, iter):
		if not self.breakDownload:
			data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
			cls = downDict[data['ID']]
			if data['downloading']  == 'Converting':
				self.gui.get_object('progressbar2').pulse()
				self.gui.get_object('progressbar2').set_text(_('Converting...'))
				self.gui.get_object('liststore3').set_value(iter, 0, gtk.gdk.pixbuf_new_from_file('img/user-away-extended.png'))
				return True
			elif data['downloading'] == 'True':
				value = cls.getProgress()
				if value[0] == 0:
					self.gui.get_object('progressbar2').pulse()
					self.gui.get_object('progressbar2').set_text(_('Preparing to download...'))
				else:
					self.gui.get_object('progressbar2').set_fraction(value[0])
					current = value[1] / 1000
					currentText = str(int(current)) + ' KB'
					if current > 2048:
						current = current / 1000
						current = "%.2f" % current
						currentText = str(current) + ' MB'
					total = value[2] / 1000
					totalText = str(int(total)) + ' KB'
					if total > 2048:
						total = total / 1000
						total = "%.2f" % total
						totalText = str(total) + ' MB'
					descarcarexyz = _('Downloading, %(currentText)s of %(totalText)s') % {'currentText' : currentText, 'totalText' :totalText}
					self.gui.get_object('progressbar2').set_text(descarcarexyz)
				return True
			elif data['downloading'] == 'Full':
				self.gui.get_object('progressbar2').set_fraction(1)
				self.gui.get_object('progressbar2').set_text(_('Download successfull.'))
				return False
		else:
			self.breakDownload = False
			return False
	
	def succes(self, iter, run=False):
		self.gui.get_object('liststore3').set_value(iter, 0, gtk.gdk.pixbuf_new_from_file('img/done.png'))
		data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
		data['downloading'] = 'Full'
		self.gui.get_object('liststore3').set_value(iter, 2, data)
		#self.gui.get_object('button6').set_sensitive(True)
		self.showDD(self.gui.get_object('treeview3'))
		if run != False:
			if platform.system() == 'Linux':
				subprocess.call(['xdg-open', run])
			else:
				os.startfile(run)
				
	def error(self, iter, e):
		self.gui.get_object('liststore3').set_value(iter, 0, gtk.gdk.pixbuf_new_from_file('img/error.png'))
		data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
		data['downloading'] = 'Error'
		self.gui.get_object('liststore3').set_value(iter, 2, data)
		#self.gui.get_object('button6').set_sensitive(True)
		self.showDD(self.gui.get_object('treeview3'))
		self.gui.get_object('progressbar2').set_fraction(0)
		self.gui.get_object('progressbar2').set_text('')
		gtk.gdk.threads_enter()
		dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('An error occured while downloading file. Debug info:') + '\n\n '+str(e)+'');
		dialog.set_title(_('Error'));
		dialog.run();
		dialog.destroy();
		gtk.gdk.threads_leave()

	def openFile(self, obj, event=None):
		treeselection = self.gui.get_object('treeview3').get_selection()
		(model, iter) = treeselection.get_selected()
		data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
		run = data['saveas']
		if platform.system() == 'Linux':
			subprocess.call(['xdg-open', run])
		else:
			os.startfile(run)
			
	def openFolder(self, obj, event = None):
		treeselection = self.gui.get_object('treeview3').get_selection()
		(model, iter) = treeselection.get_selected()
		data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
		savedAs = data['saveas']
		folder = os.path.dirname(savedAs)
		if platform.system() == 'Linux':
			subprocess.call(['xdg-open', folder])
		else:
			os.startfile(folder)
	
	def updprogess(self, size, loc):
		csize = int(os.path.getsize(loc))
		value = 0.0
		value = float(csize) / float(size)
		if value == 0:
		    self.gui.get_object('progressbar2').pulse()
		else:
		    self.gui.get_object('progressbar2').set_fraction(value)
		    
	def converter(self, tmp, saveAs, doConvert):
		self.converting = False
		if os.environ.get("APPDATA"):
			startupinfo = subprocess.STARTUPINFO()
			startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
		if doConvert == 'audio':
			if saveAs[-3:] != 'mp3':
				saveAs = saveAs + '.mp3'
			self.converting = True
			treeselection = self.gui.get_object('treeview3').get_selection()
			(model, iter) = treeselection.get_selected()
			data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
			data['downloading'] = 'Converting'
			self.gui.get_object('liststore3').set_value(iter, 2, data)
			if os.environ.get("APPDATA"):
				try:
					execstring = config.get('General', 'ffmpegAudio')
				except:
					execstring = '-i INPUT -acodec libmp3lame -ab 128k OUTPUT'
				execstring = execstring.replace('INPUT', '"'+tmp+'"')
				execstring = execstring.replace('OUTPUT', '"'+saveAs+'"')
				self.ffp = subprocess.Popen(ffmpeg + ' -y ' + execstring, startupinfo=startupinfo)
				#Thread(target=self.conversionProgress, args=(p,)).start();
				self.ffp.wait()
			else:
				try:
					execstring = config.get('General', 'ffmpegAudio')
				except:
					execstring = '-i INPUT -acodec libmp3lame -ab 128k OUTPUT'
				execs = execstring.split()
				execs[execs.index('INPUT')] = tmp
				execs[execs.index('OUTPUT')] = saveAs
				execs.insert(0, ffmpeg)
				execs.insert(1, '-y')
				#inputfile = execstring.replace('INPUT', tmp)
				#outputfile = execstring.replace('OUTPUT', "'"+saveAs+"'")
				self.ffp = subprocess.Popen(execs)
				#Thread(target=self.conversionProgress, args=(p,)).start();
				self.ffp.wait()
			self.converting = False
		elif doConvert == 'video':
			if saveAs[-3:] != 'avi':
				saveAs = saveAs + '.avi'
			self.converting = True
			treeselection = self.gui.get_object('treeview3').get_selection()
			(model, iter) = treeselection.get_selected()
			data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
			data['downloading'] = 'Converting'
			self.gui.get_object('liststore3').set_value(iter, 2, data)
			if os.environ.get("APPDATA"):
				try:
					execstring = config.get('General', 'ffmpegVideo')
				except:
					execstring = '-i INPUT -vcodec msmpeg4 -qmax 8 -acodec libmp3lame OUTPUT'
				execstring = execstring.replace('INPUT', '"'+tmp+'"')
				execstring = execstring.replace('OUTPUT', '"'+saveAs+'"')
				self.ffp = subprocess.Popen(ffmpeg + ' -y ' + execstring, startupinfo=startupinfo)
				#Thread(target=self.conversionProgress, args=(p,)).start();
				self.ffp.wait()
				saveAs = saveAs
			else:
				try:
					execstring = config.get('General', 'ffmpegVideo')
				except:
					execstring = '-i INPUT -vcodec msmpeg4 -qmax 8 -acodec libmp3lame -ab 128k OUTPUT'
				execs = execstring.split()
				execs[execs.index('INPUT')] = tmp
				execs[execs.index('OUTPUT')] = saveAs
				execs.insert(0, ffmpeg)
				execs.insert(1, '-y')
				#inputfile = execstring.replace('INPUT', tmp)
				#outputfile = execstring.replace('OUTPUT', "'"+saveAs+"'")
				self.ffp = subprocess.Popen(execs)
				#Thread(target=self.conversionProgress, args=(p,)).start();
				self.ffp.wait()
			self.converting = False
		else:
			pass
		self.doConvert = False
		    
	def conversionProgress(self, proc):
		while proc.poll() == None:
			self.gui.get_object('progressbar2').pulse()
			time.sleep(0.2)
	
	def elimina(self, obj):
		self.breakDownload = True
		treeselection = self.gui.get_object('treeview3').get_selection()
		(model, iter) = treeselection.get_selected()
		data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
		cls = downDict[data['ID']]
		cls.breakDownload = True;
		try:
			self.ffp.terminate()
		except:
			pass
		model.remove(iter)
		self.gui.get_object('label39').set_text('')
		self.gui.get_object('label40').set_text('')
		self.gui.get_object('progressbar2').set_fraction(0)
		self.gui.get_object('button17').set_sensitive(False)
		self.gui.get_object('button6').set_sensitive(False)
		self.gui.get_object('menuitem11').set_sensitive(False)
		self.gui.get_object('menuitem12').set_sensitive(False)
		self.gui.get_object('menuitem15').set_sensitive(False)
		self.gui.get_object('progressbar2').set_text('')
		
	def deletehdd(self, obj):
		initLangs()
		dialog = gtk.MessageDialog(parent=self.gui.get_object('pymaxe'), flags=0, type=gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format=_('You are about to delete this file from your computer. Continue?'));
		dialog.set_title(_('Question'));
		resp = dialog.run();
		if resp == -9:
			dialog.destroy();
			return
		dialog.destroy();
		self.breakDownload = True
		treeselection = self.gui.get_object('treeview3').get_selection()
		(model, iter) = treeselection.get_selected()
		data = eval(self.gui.get_object('liststore3').get_value(iter, 2))
		saveas = data['saveas']
		cls = downDict[data['ID']]
		cls.breakDownload = True;
		try:
			self.ffp.terminate()
		except:
			pass
		model.remove(iter)
		self.gui.get_object('label39').set_text('')
		self.gui.get_object('label40').set_text('')
		self.gui.get_object('progressbar2').set_fraction(0)
		self.gui.get_object('button17').set_sensitive(False)
		self.gui.get_object('button6').set_sensitive(False)
		self.gui.get_object('menuitem11').set_sensitive(False)
		self.gui.get_object('menuitem12').set_sensitive(False)
		self.gui.get_object('menuitem15').set_sensitive(False)
		self.gui.get_object('progressbar2').set_text('')
		try:
			if os.path.exists(saveas):
				os.remove(saveas)
		except:
			initLangs()
			dialog = gtk.MessageDialog(parent=self.gui.get_object('pymaxe'), flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('Cannot delete file: ') + saveas);
			dialog.set_title(_('Error'));
			resp = dialog.run();
			dialog.destroy();
		
	def on_preferences(self, obj):
		self.readPreferences()
		self.gui.get_object('button11').set_sensitive(False)
		self.gui.get_object('button14').set_sensitive(False)
		self.gui.get_object('preferinte').show()
		self.gui.get_object('preferinte').present()
		
	def hide_settings(self, obj, event=None):
		self.gui.get_object('preferinte').hide()
		return True
		
	def hide_plugin(self, obj, event=None):
		self.gui.get_object('pdetail').hide()
		return True
		
	def readPreferences(self):
		config.read(cfgfile)
		try:
			streamPlayer = config.get('General', 'streamPlayer')
		except:
			streamPlayer = ''
		self.gui.get_object('entry7').set_text(streamPlayer)
		
		try:
			saveIn = config.get('General', 'saveIn')
		except:
			if os.environ.get("USERPROFILE"):
				saveIn = os.environ.get("USERPROFILE") + '\\Desktop'
			else:
				saveIn = os.environ.get("HOME") + '/Desktop'
		self.gui.get_object('entry4').set_text(saveIn)
		
		try:
			noConvert = config.getboolean('General', 'noConvert')
		except:
			noConvert = False
		self.gui.get_object('checkbutton1').set_active(noConvert)
		
		try:
			autoOpen = config.getboolean('General', 'autoOpen')
		except:
			autoOpen = True		
		self.gui.get_object('checkbutton2').set_active(autoOpen)
		
		try:
			splashScreen = config.getboolean('General', 'splashScreen')
		except:
			splashScreen = True
		self.gui.get_object('checkbutton3').set_active(splashScreen)
		try:
			ffmpegAudio = config.get('General', 'ffmpegAudio')
		except:
			if os.environ.get("APPDATA"):
				ffmpegAudio = '-i INPUT -acodec libmp3lame -ab 128k OUTPUT'
			else:
				ffmpegAudio = '-i INPUT -acodec libmp3lame -ab 128k OUTPUT'
		
		self.gui.get_object('entry5').set_text(ffmpegAudio)
		
		try:
			ffmpegVideo = config.get('General', 'ffmpegVideo')
		except:
			if os.environ.get("APPDATA"):
				ffmpegVideo = '-i INPUT -vcodec msmpeg4 -qmax 8 -acodec libmp3lame OUTPUT'
			else:
				ffmpegVideo = '-i INPUT -vcodec msmpeg4 -qmax 8 -acodec libmp3lame -ab 128 OUTPUT'
		self.gui.get_object('entry6').set_text(ffmpegVideo)
		try:
			checkUpdates = config.getboolean('General', 'checkUpdates')
		except:
			checkUpdates = True
		self.gui.get_object('checkbutton4').set_active(checkUpdates)
		try:
			updatePlugins = config.getboolean('General', 'updatePlugins')
		except:
			updatePlugins = True
		self.gui.get_object('checkbutton5').set_active(updatePlugins)
		try:
			self.plugins = config.get("Plugins", 'plugins');
		except:
			pFiles = os.listdir('plugins')
			sys.path.append('plugins')
			plist = []
			for fname in pFiles:
				plist.append(fname)
			if 'ThemeConfig' in plist:
				plist.pop(plist.index('ThemeConfig'))
			if 'YouTube' in plist:
				plist.pop(plist.index('YouTube'))
			plugins = ';'.join(plist)
			config.set('Plugins', 'plugins', plugins)
		self.plist = self.gui.get_object("liststore2");
		self.plist.clear();
		plugins = self.plugins.split(';')
		self.plugin = {}
		if os.environ.get("APPDATA"):
			pFilesp = os.listdir(os.environ.get("APPDATA") + '\\pymaxe\\plugins')
			sys.path.append(os.environ.get("APPDATA") + '\\pymaxe\\plugins')
		else:
			pFilesp = os.listdir(os.getenv("HOME") + '/.pymaxe/plugins')
			sys.path.append(os.getenv("HOME") + '/.pymaxe/plugins')
		pFiless = os.listdir('plugins')
		sys.path.append('plugins')
		self.plist.clear();
		for plugin in pFilesp:
			try:
				self.plugin[plugin] = __import__(plugin)
				self.plugin[plugin] = self.plugin[plugin].Main()
				if plugin in plugins:
					try:
						self.plist.append([True, self.plugin[plugin].pluginName, self.plugin[plugin].version, plugin]);
					except:
						plugloadfailedstr = _('WARNING! Plugin \'%s\' could not be started. Loading aborted.') % plugin
						print plugloadfailedstr
				else:
						self.plist.append([False, self.plugin[plugin].pluginName, self.plugin[plugin].version, plugin]);
			except Exception, e:
				plugloadfailedstr = _('WARNING! Plugin \'%s\' could not be started. Loading aborted.') % plugin
				print plugloadfailedstr
		for plugin in pFiless:
			try:
				if not self.plugin.has_key(plugin):
					self.plugin[plugin] = __import__(plugin)
					self.plugin[plugin] = self.plugin[plugin].Main()
					if plugin in plugins:
						try:
							self.plist.append([True, self.plugin[plugin].pluginName, self.plugin[plugin].version, plugin]);
						except Exception, e:
							plugloadfailedstr = _('WARNING! Plugin \'%s\' could not be started. Loading aborted.') % plugin
							print plugloadfailedstr
							print e
					else:
							self.plist.append([False, self.plugin[plugin].pluginName, self.plugin[plugin].version, plugin]);
			except Exception, e:
				plugloadfailedstr = _('WARNING! Plugin \'%s\' could not be started. Loading aborted.') % plugin
				print plugloadfailedstr	
				print e
		initLangs()
	
	def activateCheck(self, obj, key):
		model = self.gui.get_object('liststore2')
		if model[key][0]:
			self.plugin[model[key][3]].uninstall(self)
			model[key][0] = False
		else:
			self.plugin[model[key][3]].start(self)
			model[key][0] = True
		initLangs()
			
	def select_folder(self, obj):
		chooser = gtk.FileChooserDialog(title=_('Save in...'),action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
                chooser.set_do_overwrite_confirmation(True)
		chooser.set_current_folder(os.path.dirname(self.gui.get_object('entry4').get_text()))
                response = chooser.run()
                if response == gtk.RESPONSE_OK:
			self.gui.get_object('entry4').set_text(chooser.get_filename())
		chooser.destroy()
		
	def saveSettings(self, obj):
		config.set('General', 'saveIn', self.gui.get_object('entry4').get_text())
		config.set('General', 'noConvert', self.gui.get_object('checkbutton1').get_active())
		config.set('General', 'autoOpen', self.gui.get_object('checkbutton2').get_active())
		config.set('General', 'splashScreen', self.gui.get_object('checkbutton3').get_active())
		config.set('General', 'ffmpegAudio', self.gui.get_object('entry5').get_text())
		config.set('General', 'ffmpegVideo', self.gui.get_object('entry6').get_text())
		config.set('General', 'checkUpdates', self.gui.get_object('checkbutton4').get_active())
		config.set('General', 'updatePlugins', self.gui.get_object('checkbutton5').get_active())
		config.set('General', 'streamPlayer', self.gui.get_object('entry7').get_text())
		liststore = self.gui.get_object('liststore2')
		iter = liststore.get_iter_root()
		plist = []
		while (iter):
			pluginName = liststore.get_value(iter, 3)
			checked = liststore.get_value(iter, 0)
			if checked:
				plist.append(pluginName)
			iter = liststore.iter_next(iter)
		
		plugins = ';'.join(plist)
		config.set('Plugins', 'plugins', plugins)
	
		"""pFiles = os.listdir('./plugins')
		sys.path.append('./plugins')
		plist = []
		for fname in pFiles:
			plist.append(fname)
	
		plugins = ';'.join(plist)

		config.set('Plugins', 'plugins', plugins)"""
		
		fHandler = open(cfgfile, "wb")
		config.write(fHandler)
		fHandler.close()
		config.read(cfgfile)
		self.hide_settings(obj)
		
	def removePlugin(self, obj):
		plugintree = self.gui.get_object('treeview2')
		treeselection = plugintree.get_selection()
		model, selectat = treeselection.get_selected()
		pluginModule = self.gui.get_object('liststore2').get_value(selectat, 3);
		self.gui.get_object('liststore2').remove(selectat);
		self.plugin[pluginModule].uninstall(self)
		try:
			del self.sites[pluginModule]
			del self.plugin[pluginModule]
		except:
			print _("Uninstallation failed. Please restart the application.")
		initLangs()
	
	def plugin_details(self, obj, event=None):
		if obj == self.gui.get_object('button11') or event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
			plugintree = self.gui.get_object('treeview2')
			treeselection = plugintree.get_selection()
			(model, iter) = treeselection.get_selected()
			if iter:
				pluginModule = self.gui.get_object('liststore2').get_value(iter, 3);
				pluginName = self.plugin[pluginModule].pluginName
				pluginAuthor = self.plugin[pluginModule].author
				pluginVersion = self.plugin[pluginModule].version
				pluginDesc = self.plugin[pluginModule].descriere
				self.gui.get_object('label17').set_markup('<span size="x-large"><b>'+pluginName+'</b></span>')
				self.gui.get_object('label18').set_markup(_('<b>Author:</b> %s') % pluginAuthor)
				self.gui.get_object('label19').set_markup(_('<b>Version:</b> %s') % pluginVersion)
				self.gui.get_object('label20').set_markup('<i>'+pluginDesc+'</i>')
				self.gui.get_object('pdetail').set_title(pluginName)
				self.gui.get_object('pdetail').show()
		initLangs()
			
	def pluginConfig(self, obj):
		plugintree = self.gui.get_object('treeview2')
		treeselection = plugintree.get_selection()
		(model, iter) = treeselection.get_selected()
		if iter:
			pluginModule = self.gui.get_object('liststore2').get_value(iter, 3);
			self.plugin[pluginModule].config(self)
		initLangs()
			
	def activateTree(self, obj, event=False):
		self.isWorking = False
		self.treeview.set_sensitive(True)
		self.gui.get_object('toolbar1').set_sensitive(True)
		self.gui.get_object('menubar1').set_sensitive(True)
		self.gui.get_object('scrolledwindow1').set_sensitive(True)
	
	def restoreState(self):
		gobject.idle_add(self.treeview.set_sensitive, True)
		gobject.idle_add(self.gui.get_object('toolbar1').set_sensitive, True)
		gobject.idle_add(self.gui.get_object('menubar1').set_sensitive, True)
		gobject.idle_add(self.gui.get_object('notebook2').set_sensitive, True)
		self.gui.get_object('scrolledwindow1').set_sensitive(True)
		
	def splashClick(self, obj, event):
		if platform.system() == 'Linux':
			subprocess.call(['xdg-open', 'http://www.primariagh.ro/?page_id=546'])
		else:
			os.startfile('http://www.primariagh.ro/?page_id=546')
			
	def openSourceWWW(self, obj):
		treeselection = self.treeview.get_selection()
		(model, iter) = treeselection.get_selected()
		url = self.liststore.get_value(iter, 3)
		Thread(target=self.openSourceWWWinBrowser, args=(url, )).start()
		
	def openSourceWWWinBrowser(self, url):
		for x in self.sites:
			mask = self.sites[x]
			if url.find(mask) != -1:
				fileData = self.plugin[x].fileData(url)
				break
		if fileData:
			url = fileData['url']
			if platform.system() == 'Linux':
				subprocess.call(['xdg-open', url])
			else:
				os.startfile(url)
		else:
			gtk.gdk.threads_enter()
			dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('Source URL cannot be fetch.'));
			dialog.set_title(_('Can\'t open :('));
			dialog.run();
			dialog.destroy();
			gtk.gdk.threads_leave()
			return False
		initLangs()
		
	def copyStreamURL(self, obj):
		treeselection = self.treeview.get_selection()
		(model, iter) = treeselection.get_selected()
		url = self.liststore.get_value(iter, 3)
		clipboard = gtk.Clipboard()
		Thread(target=self.copyStreamURLtoClipboard, args=(url, clipboard)).start()
				
	def copyStreamURLtoClipboard(self, url, clipboard):
		for x in self.sites:
			mask = self.sites[x]
			if url.find(mask) != -1:
				break
		getURL = self.plugin[x].fileData(url)
		if getURL:
			gobject.idle_add(clipboard.set_text, getURL['downurl'], -1)
		else:
			gtk.gdk.threads_enter()
			dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('Stream URL cannot be fetch.'));
			dialog.set_title(_('Can\'t open :('));
			dialog.run();
			dialog.destroy();
			gtk.gdk.threads_leave()
			return False
		initLangs()
		
	def showStream(self, obj):
		player = self.gui.get_object('entry7').get_text()
		if player == '':
			dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('No player defined for playing streams.'));
			dialog.set_title(_('Can\'t open :('));
			dialog.run();
			dialog.destroy();
			return False
		
		treeselection = self.treeview.get_selection()
		(model, iter) = treeselection.get_selected()
		url = self.liststore.get_value(iter, 3)
		Thread(target=self.startPlayer, args=(url, player)).start()
		
	def startPlayer(self, url, player):
		for x in self.sites:
			mask = self.sites[x]
			if url.find(mask) != -1:
				break
		getURL = self.plugin[x].fileData(url)
		if getURL:
			try:
				subprocess.Popen([player, getURL['downurl']])
			except Exception, e:
				gtk.gdk.threads_enter()
				dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('Cannot execute player defined for playing streams. Please check your settings.'));
				dialog.set_title(_('Can\'t open :('));
				dialog.run();
				dialog.destroy();
				gtk.gdk.threads_leave()
				print e
				return False
		else:
			gtk.gdk.threads_enter()
			dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('Source URL cannot be fetch.'));
			dialog.set_title(_('Can\'t open :('));
			dialog.run();
			dialog.destroy();
			gtk.gdk.threads_leave()
			return False
		initLangs()
			
	def clearSearchEntry(self, obj, event=None):
		if self.gui.get_object('entry1').get_text() == self.entry1text:
			self.gui.get_object('entry1').modify_font(pango.FontDescription("Normal"))
			self.gui.get_object('entry1').set_text('')
			
	def resetEntryStyle(self, obj):
		self.gui.get_object('entry1').modify_font(pango.FontDescription("Normal"))
			
	def pluginInstall(self, obj):
		chooser = gtk.FileChooserDialog(title=_('Install plugin...'),action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
                if os.environ.get("APPDATA"):
                	chooser.set_current_folder(os.environ.get("USERPROFILE") + '\\Desktop')
                else:
	                chooser.set_current_folder(os.getenv("HOME") + '/Desktop')
                response = chooser.run()
                if response == gtk.RESPONSE_OK:
			self.doPluginInstall(chooser.get_filename())
		chooser.destroy()
		
	def doPluginInstall(self, path, notify = True):
		try:
			archive = zipfile.ZipFile(path)
			if os.environ.get("APPDATA"):
				installPath = os.environ.get("APPDATA") + '\\pymaxe\\plugins'
			else:
				installPath = os.getenv("HOME") + '/.pymaxe/plugins'
			filelist = archive.namelist()
			valid = False
			for name in filelist:
				if name.find('__init__') != -1:
					valid = True
			if valid == True:
				for name in filelist:
					if name.endswith('/'):
						if not os.path.exists(installPath + '/' + name):
							os.mkdir(os.path.join(installPath, name))
					else:
						outfile = open(os.path.join(installPath, name), 'wb')
						outfile.write(archive.read(name))
						outfile.close()
				if notify:
					dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_CLOSE, message_format=_('Plugin successfully installed!'));
					dialog.set_title(_('Install plugin'));
					dialog.run();
					dialog.destroy();
				plugin = filelist[0][:-1]
				liststore = self.gui.get_object('liststore2')
				iter = liststore.get_iter_first()
				isExists = False
				while (iter):
					if liststore.get_value(iter, 1) == plugin:
						isExists = iter
						break
					iter = liststore.iter_next(iter)
				try:
					if isExists != False:
						del sys.modules[plugin]
					newplugin = __import__(plugin)
					self.plugin[plugin] = newplugin.Main()
					#self.plugin[plugin].start()
				except Exception, e:
					print _('Warning! Plugin cannot be started. It is possible to must restart the application to get the new plugin to work.')
					print e
				if isExists == False:
					self.plist.append([False, self.plugin[plugin].pluginName, self.plugin[plugin].version, plugin]);
				else:
					self.plugin[plugin].start(self)
					liststore.set(isExists, 2, self.plugin[plugin].version)
			else:
				if notify:
					dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('The plugin that you wish to install doesn\'t seem to be valid. (missing INIT file)'));
					dialog.set_title(_('Install plugin'));
					dialog.run();
					dialog.destroy();
		except Exception, e:
			if notify:
				dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_('The plugin that you wish to install doesn\'t seem to be valid.') + ' ('+str(e)+')');
				dialog.set_title(_('Install plugin'));
				dialog.run();
				dialog.destroy();
		initLangs()	
			
		
	def chooseMP(self, obj):
		chooser = gtk.FileChooserDialog(title=_('Select an executable file...'),action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
                if os.environ.get("APPDATA"):
                	chooser.set_current_folder(os.environ.get("ProgramFiles"))
			filter = gtk.FileFilter()
			filter.set_name(_("Executable"))
			filter.add_pattern("*.exe")
                else:
	                chooser.set_current_folder('/usr/bin')
      			filter = gtk.FileFilter()
			filter.set_name(_("Executable"))
			filter.add_mime_type("application/octet-stream")
		chooser.add_filter(filter)
                response = chooser.run()
                if response == gtk.RESPONSE_OK:
			self.gui.get_object('entry7').set_text(chooser.get_filename())
		chooser.destroy()
		
	def cancelOperation(self, obj):
		self.isWorking = False
		self.gui.get_object('hbox25').hide()
		self.restoreState()
		try:
			self.searchThread.terminate()
			self.searchThread = None
		except:
			self.searchThread = None
		try:
			self.detailsThread.terminate()
			self.detailsThread = None
		except:
			self.detailsThread = None
		try:
			for x in self.searchThreads:
				try:
					x.terminate()
					self.searchThread = None
				except:
					self.searchThread = None
		except:
			pass
			
	def updatePluginsButtons(self, obj):
		plugintree = self.gui.get_object('treeview2')
		treeselection = plugintree.get_selection()
		(model, iter) = treeselection.get_selected()
		if iter:
			pluginModule = self.gui.get_object('liststore2').get_value(iter, 3);
			self.gui.get_object('button11').set_sensitive(True)
			if hasattr(self.plugin[pluginModule], "config"):
				self.gui.get_object('button14').set_sensitive(True)
			else:
				self.gui.get_object('button14').set_sensitive(False)
					
		
	# pentru plugin-uri
	def getSetting(self, section, setting):
		try:
			return config.get(section, setting)
		except Exception, e:
			return None
	
	def setSetting(self, section, setting, value):
		config.set(section, setting, value)
		fHandler = open(cfgfile, "wb")
		config.write(fHandler)
		fHandler.close()
		
	###########

	def on_pymaxe_destroy(self, obj, event=None):
		liststore = self.gui.get_object('liststore3')
		iterr = liststore.get_iter_root()
		dwns = 0
		while iterr:
			data = eval(liststore.get_value(iterr, 2))
			if data['downloading'] != 'Full':
				dwns = dwns + 1
			iterr = liststore.iter_next(iterr)
		if dwns > 0:
			initLangs()
			dialog = gtk.MessageDialog(parent=self.gui.get_object('pymaxe'), flags=0, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_YES_NO, message_format=_('A download is still in progress. Cancel it and quit the application?'));
			dialog.set_title(_('Warning'));
			resp = dialog.run();
			dialog.destroy();
			if resp == -9:
				return True
		gobject.source_remove(self.pulsar)
		gtk.main_quit();
		os._exit(0)

class Downloader:
	def __init__(self):
		self.time = time.strftime("%H:%M:%S")

	def download(self, url, data, converter, justSave, iter, callback, err_callback):
		saveAs = data['saveas']
		saveAs = saveAs.replace('~', '-')
		ceas = datetime.datetime.now()
		if os.environ.get("APPDATA"):
			self.tmp = os.environ.get('TMP') + '\\' + str(time.mktime(ceas.timetuple()));
		else:
			self.tmp = '/tmp/' + str(time.mktime(ceas.timetuple()));
		try:
			conn = urllib2.urlopen(url)
		except Exception, e:
			gobject.idle_add(err_callback, iter, e)
			return
		try:
			self.size = conn.headers["Content-Length"]
			self.size = int(self.size)
			self.breakDownload = False;
			with open(self.tmp, 'wb') as downfile:
				while not self.breakDownload:
					downData = conn.read(10240)
					if not downData:
						downfile.close()
						doConvert = data['convert']
						if doConvert != 'False':
							converter(self.tmp, saveAs, doConvert)
						else:
							shutil.copyfile(self.tmp, saveAs)
						if not self.breakDownload:
							if justSave == True:
								gobject.idle_add(callback, iter, saveAs)
							else:
								gobject.idle_add(callback, iter)
						os.remove(self.tmp)
						break
					downfile.write(downData)
					#self.updprogess(size, self.tmp)
				else:
					return True
		except Exception, e:
			print e

	def getProgress(self):
		try:
			csize = int(os.path.getsize(self.tmp))
			value = 0.0
			value = float(csize) / float(self.size)
			return [value, float(csize), float(self.size)]
		except:
			return [0, 0, 0]
					
if __name__ == "__main__":
	if os.environ.get("APPDATA"):
		freeze_support()
		Process(target=Main).start()
	else:
		Main()
